package com.bears.god.sup.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.User;
import com.bears.god.sup.service.ServiceDAOFactory;
import com.bears.god.sup.service.UserService;
import com.bears.god.sup.util.Md5Code;

@WebServlet("/regist.do")
public class RegistServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 000001L;
	public static final String METHOD_REGIST_FROM = "0";
	public static final String METHOD_REGIST_STEP1 = "1";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method != null) {
			switch (method) {
			case RegistServlet.METHOD_REGIST_FROM:
				registTo(req, resp);
				break;

			case RegistServlet.METHOD_REGIST_STEP1:
				registStep1(req, resp);
				break;

			default:
				break;
			}
		}
	}

	private void registStep1(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

		try {
			User user = new User();
			UserService userservice = ServiceDAOFactory.getUserDAO();

			user.setEmail(req.getParameter("email"));
			user.setName(req.getParameter("name"));
			String pwd = Md5Code.createMd5Code(req.getParameter("password"));
			user.setPassword(pwd);
			user.setUserDept(req.getParameter("user_dept"));

			userservice.save(user);

			req.getSession().setAttribute("s_user", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		req.getRequestDispatcher("WEB-INF/view/manager/signup_ok.jsp").forward(req, resp);
	}

	private void registTo(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		req.getRequestDispatcher("WEB-INF/view/manager/signup.jsp").forward(req, resp);
	}
}
